/**
 * Project Name:pay-commons-core
 * File Name:IdleConnectionMonitorThread.java
 * Package Name:com.zfull.commons.utils.httpclient.common
 * Date:2018年2月1日上午11:24:31
 * Copyright (c) 2018, www.zengfull.com All Rights Reserved.
 *
*/

package com.rc.saas.payment.unwxpay.util;

import org.apache.http.conn.HttpClientConnectionManager;

import java.util.concurrent.TimeUnit;

/**
 * 空闲连接监控线程,<br/>
 * 使用某个连接前，检测这个连接是否已经失效，<br/>
 * 如果服务端关闭了连接，那么连接就会失效。<br/>
 * 这个监控只是与检测预防，不能百分百有效<br/>
 * ClassName:IdleConnectionMonitorThread <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason: TODO ADD REASON. <br/>
 * Date: 2018年2月1日 上午11:24:31 <br/>
 * 
 * @author GuangMing
 * @version
 * @since JDK 1.8 * @see
 */
public class IdleConnectionMonitorThread extends Thread {
	private final HttpClientConnectionManager connMgr;
	private volatile boolean shutdown;	

	public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {
		super();
		this.connMgr = connMgr;
	}

	@Override
	public void run() {
		try {
			while (!shutdown) {
				synchronized (this) {
					wait(180000);
					// Close expired connections
					connMgr.closeExpiredConnections();
					// Optionally, close connections
					// that have been idle longer than 180 sec
					connMgr.closeIdleConnections(180, TimeUnit.SECONDS);
				}
			}
		} catch (InterruptedException ex) {
			// terminate
		}
	}

	public void shutdown() {
		shutdown = true;
		synchronized (this) {
			notifyAll();
		}
	}
}
